/* vim:set sw=3 et ai cin: */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include "cbfxs.h"

int main(int argc, char *argv[])
{
   int fd, i;
   struct cbfxs_ioctl_spi_command cmd;
   if(argc < 2) {
      cmd.buffer[0] = 0x73;
      cmd.buffer[1] = 0;
      cmd.buffer[2] = 0;
      cmd.buffer[3] = 0;
      cmd.buffer_sz = 4;
   } else {
      int nb;
      char *pos = argv[1];
      cmd.buffer_sz = 0;
      for(nb = 0;; nb++) {
	 if(*pos == '\0') break;
	 *pos = toupper(*pos);
	 if((*pos >= '0') && (*pos <= '9')) {
	    cmd.buffer[cmd.buffer_sz] <<= 4;
	    cmd.buffer[cmd.buffer_sz] |= *pos++ - '0';
	 } else if((*pos >= 'A') && (*pos <= 'F')) {
	    cmd.buffer[cmd.buffer_sz] <<= 4;
	    cmd.buffer[cmd.buffer_sz] |= *pos++ - 'A' + 10;
	 } else break;
	 if((nb % 2) == 1) cmd.buffer_sz++;
	 if(cmd.buffer_sz >= sizeof(cmd.buffer)) break;
      }
   }
  
   fd = open("cbfxs", O_RDWR);
   if(ioctl(fd, CBFXS_IOC_SPI_COMMAND, &cmd)) {
      perror("ioctl");
   }
   printf("Result: ");
   for(i = 0; i < cmd.buffer_sz; i++) {
      printf("%02X ", cmd.buffer[i]);
   }
   printf("\n");
   close(fd);
   return 0;
}

